package com.chunfen.dubbo.register;

import com.chunfen.dubbo.framework.URL;
import com.google.common.collect.Maps;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class RemoteRegister {

    // consumer  和 provider 处于不同进程 不共用 registerMap
    private static Map<String, List<URL>> registerMap = Maps.newHashMap();

    public static void regist(String interfaceName, URL url){

        List<URL> list = Collections.singletonList(url);
        registerMap.put(interfaceName, list);

        saveFile(registerMap);
    }

    // 这里对应  dubbo 可用的服务 进行 负载均衡
    public static URL random(String interfaceName){
        // 从内存获取 url
//        List<URL> list = registerMap.get(interfaceName);

        // 从文件获取url
        List<URL> list = getFile().get(interfaceName);


        Random random = new Random();
        int n = random.nextInt(list.size());
        return list.get(n);
    }

    /**
     * 从文件中读取  map 注册信息
     * @return
     */
    private static Map<String, List<URL>> getFile(){
        try ( FileInputStream fileInputStream = new FileInputStream("temp.obj");
              ObjectInputStream ois = new ObjectInputStream(fileInputStream);){

            return ( Map<String, List<URL>>) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存 map 到文件
     * @param registerMap
     */
    private static void saveFile(Map<String, List<URL>> registerMap){
        try (FileOutputStream fos = new FileOutputStream("temp.obj");
             ObjectOutputStream oos = new ObjectOutputStream(fos)){

            oos.writeObject(registerMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
